package yns.springboot.guide.demo.controller;

import java.util.concurrent.CompletableFuture;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import yns.springboot.guide.demo.task.Task;

@RestController
public class TestAsyncController extends BaseController {
	
	// http://localhost:8080/task
	// http://localhost:8080/task2
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private Task task;

	@RequestMapping("/task")
	public String testTask() {
		logger.info(httpServletRequest.getRequestURI());
		
		try {
			CompletableFuture<String> taskOne = task.doTaskOne();
			CompletableFuture<String> taskTwo = task.doTaskTwo();
			CompletableFuture<String> taskThree = task.doTaskThree();
				
			long start = System.currentTimeMillis();
			boolean flag = false;
			while (true) {
				flag = taskOne.isDone() && taskTwo.isDone() && taskThree.isDone();
				if (flag) {
					break;
				}
				Thread.sleep(100);
			}

			long end = System.currentTimeMillis();
			logger.info("total time : " + (end - start) );
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return "TestAsync";
	}

	@RequestMapping("/task2")
	public String testTask2() {
		logger.info(httpServletRequest.getRequestURI());

		try {
			CompletableFuture<String> taskOne = task.doTaskOne();
			CompletableFuture<String> taskTwo = task.doTaskTwo();
			CompletableFuture<String> taskThree = task.doTaskThree();
			
			CompletableFuture.allOf(taskOne,taskTwo,taskThree).join();
			
			logger.info("taskOne : " + taskOne.get() + " taskTwo : " + taskTwo.get() + " taskThree : " + taskThree.get());

		} catch (Exception e) {
			e.printStackTrace();
		}

		return "TestAsync2";
	}
}
